import React from 'react'
import {
  Form,
  Input,
  Tooltip,
  Icon,
  Cascader,
  Select,
  Row,
  Col,
  Checkbox,
  Button,
  AutoComplete,
  Card,

} from 'antd';

const {Option} = Select;
const {TextArea} = Input;

const residences = [
  {
    value: 'zhejiang',
    label: 'Zhejiang',
    children: [
      {
        value: 'hangzhou',
        label: 'Hangzhou',
        children: [
          {
            value: 'xihu',
            label: 'West Lake',
          },
        ],
      },
    ],
  },
  {
    value: 'jiangsu',
    label: 'Jiangsu',
    children: [
      {
        value: 'nanjing',
        label: 'Nanjing',
        children: [
          {
            value: 'zhonghuamen',
            label: 'Zhong Hua Men',
          },
        ],
      },
    ],
  },
];

export default Form.create({name: 'register'})(class RegistrationForm extends React.Component {
    state = {
      confirmDirty: false,
      autoCompleteResult: [],
      result: []
    };

    handleSubmit = e => {
      e.preventDefault();
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values);
        }
      });
    };

    handleConfirmBlur = e => {
      const value = e.target.value;
      this.setState({confirmDirty: this.state.confirmDirty || !!value});
    };

    compareToFirstPassword = (rule, value, callback) => {
      const form = this.props.form;
      if (value && value !== form.getFieldValue('password')) {
        callback('Two passwords that you enter is inconsistent!');
      } else {
        callback();
      }
    };

    validateToNextPassword = (rule, value, callback) => {
      const form = this.props.form;
      if (value && this.state.confirmDirty) {
        form.validateFields(['confirm'], {force: true});
      }
      callback();
    };

    render() {
      const {getFieldDecorator} = this.props.form;
      const {autoCompleteResult} = this.state;

      const formItemLayout = {
        labelCol: {
          xs: {span: 24},
          sm: {span: 3},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 12},
        },
      };
      const tailFormItemLayout = {
        wrapperCol: {
          xs: {
            span: 24,
            offset: 0,
          },
          sm: {
            span: 12,
            offset: 3,
          },
        },
      };
      const prefixSelector = getFieldDecorator('prefix', {
        initialValue: '86',
      })(
        <Select style={{width: 70}}>
          <Option value="86">+86</Option>
          <Option value="87">+87</Option>
        </Select>,
      );


      return (
        <Card style={{marginTop: 10}}>
          <Form layout="vertical"  {...formItemLayout} onSubmit={this.handleSubmit}>
            <Form.Item label="E-mail">
              {getFieldDecorator('email1', {
                rules: [
                  {
                    type: 'email',
                    message: 'The input is not valid E-mail!',
                  },
                  {
                    required: true,
                    message: 'Please input your E-mail!',
                  },
                ],
              })(<Input/>)}
            </Form.Item>
            <Form.Item label="Password" hasFeedback>
              {getFieldDecorator('password', {
                rules: [
                  {
                    required: true,
                    message: 'Please input your password!',
                  },
                  {
                    validator: this.validateToNextPassword,
                  },
                ],
              })(<Input.Password/>)}
            </Form.Item>
            <Form.Item label="Confirm Password" hasFeedback>
              {getFieldDecorator('confirm', {
                rules: [
                  {
                    required: true,
                    message: 'Please confirm your password!',
                  },
                  {
                    validator: this.compareToFirstPassword,
                  },
                ],
              })(<Input.Password onBlur={this.handleConfirmBlur}/>)}
            </Form.Item>
            <Form.Item hasFeedback
                       label={
                         <span>
                            Nickname&nbsp;
                           <Tooltip title="What do you want others to call you?">
                                <Icon type="question-circle-o"/>
                            </Tooltip>
                        </span>
                       }
            >
              {getFieldDecorator('nickname', {
                rules: [{required: true, message: 'Please input your nickname!', whitespace: true}],
              })(<Input/>)}
            </Form.Item>
            <Form.Item label="Habitual Residence">
              {getFieldDecorator('residence', {
                initialValue: ['zhejiang', 'hangzhou', 'xihu'],
                rules: [
                  {type: 'array', required: true, message: 'Please select your habitual residence!'},
                ],
              })(<Cascader options={residences}/>)}
            </Form.Item>
            <Form.Item label="Phone Number">
              {getFieldDecorator('phone', {
                rules: [{required: true, message: 'Please input your phone number!'}],
              })(<Input addonBefore={prefixSelector} style={{width: '100%'}}/>)}
            </Form.Item>


            <Form.Item label="网站">
              {getFieldDecorator('website', {
                rules: [{required: true, message: 'Please input website!'}],
              })(
                <AutoComplete
                  dataSource={autoCompleteResult.map(website => (
                    <AutoComplete.Option key={website}>{website}</AutoComplete.Option>
                  ))}
                  onChange={value => {
                    let autoCompleteResult;
                    if (!value) {
                      autoCompleteResult = [];
                    } else {
                      autoCompleteResult = ['.com', '.kim', '.org', '.net', '.cn'].map(domain => `${value}${domain}`);
                    }
                    this.setState({autoCompleteResult});
                  }}
                  placeholder="website"
                >
                  <Input/>
                </AutoComplete>,
              )}
            </Form.Item>

            <Form.Item label="邮箱" {...formItemLayout} >
              {
                this.props.form.getFieldDecorator('email', {
                  initialValue: '',
                  rules: [{required: true, message: 'email不能为空'},
                  ]
                })(
                  <AutoComplete
                    onSearch={value => {
                      let result;
                      if (!value || value.indexOf('@') >= 0) {
                        result = [];
                      } else {
                        result = ['gmail.com', '163.com', 'qq.com'].map(domain => `${value}@${domain}`);
                      }
                      this.setState({result});
                    }}
                    placeholder="email"
                  >
                    {this.state.result.map(email => <Option key={email}>{email}</Option>)}
                  </AutoComplete>
                )
              }
            </Form.Item>

            <Form.Item label="Captcha" extra="We must make sure that your are a human.">
              <Row gutter={8}>
                <Col span={12}>
                  {getFieldDecorator('captcha', {
                    rules: [{required: true, message: 'Please input the captcha you got!'}],
                  })(<Input/>)}
                </Col>
                <Col span={12}>
                  <Button>Get captcha</Button>
                </Col>
              </Row>
            </Form.Item>
            <Form.Item {...tailFormItemLayout}>
              {getFieldDecorator('agreement', {
                valuePropName: 'checked',
              })(
                <Checkbox>
                  I have read the <a href="">agreement</a>
                </Checkbox>,
              )}
            </Form.Item>

            <Form.Item {...tailFormItemLayout}>
              <Button type="primary" htmlType="submit" style={{width: "100%"}} onClick={() => {
                console.log(this.props.form.getFieldsValue())
              }}>
                Register
              </Button>
            </Form.Item>

            <Form.Item {...tailFormItemLayout}>
              <TextArea placeholder="" autosize={{minRows: 2, maxRows: 6}} rows={6}/>
            </Form.Item>

          </Form>

        </Card>
      );
    }
  }
)
